<?php

require_once('jhtraq.php');
class JhtraqModelUser extends JhtraqModelJhtraq
{
	
	function getPaged()
	{
		$mainframe =& JFactory::getApplication();
		$limit = $mainframe->getUserStateFromRequest( 'global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int' );
		$limitstart = JRequest::getVar('limitstart', 0, '', 'int');
		jimport('joomla.html.pagination');
		$search = JRequest::getVar('search');
		
		$query = "Select SQL_CALC_FOUND_ROWS * from #__jhtraq_users as tu left join #__users as u on tu.id=u.id";
		if($search != '')
		$query .= " Where u.username like '%$search%' or u.email like '%$search%' ";
		$query .= " Order by u.username asc";
		//echo $query;
		$this->db->setQuery($query,$limitstart, $limit );
		$r =&$this->db->loadAssocList();
		
		$this->db->setQuery('SELECT FOUND_ROWS();');
		$this->_pagination = new JPagination( $this->db->loadResult(), $limitstart, $limit );
		
		return $r;
	}
	
	function setGid($id,$gid)
	{
		$this->db->setQuery("Update #__jhtraq_users set group_id='$gid' where id='$id'");
		return $this->db->query();
	}
	
	function get($uid = 0)
	{
		$this->db->setQuery("Select * from #__jhtraq_users as tq left join #__users as u on tq.id=u.id where u.id='$uid'");
		return  $this->db->loadObject();
	}
	
	function save($group)
	{
		if((int)$group->id == 0)
		{
			$this->db->setQuery("Insert into #__jhtraq_usergroups set name='".$this->db->getEscaped($group->name)."'");
		}else{
			$this->db->setQuery("Update #__jhtraq_usergroups set name='".$this->db->getEscaped($group->name)."' where id='".$group->id."'");
		}
		$this->db->query();
	}
	
	function remove($group)
	{
		$this->db->setQuery("Delete from #__jhtraq_usergroups where id='".$group."'");
		$this->db->query();
	}
	
	/**
	 * @name getAll
	 * @param none
	 * @return array
	 */
	function getAll()
	{
			$this->db->setQuery("Select id,username from #__users order by username asc");
			$res = $this->db->loadAssocList();
			$return = array();
			foreach($res as $row)
			{
				$return[$row['id']] = $row['username'];
			}
			return $return;
	}
	
	/**
	 * @name count
	 * @param none
	 * @return int
	 */
	function count()
	{
		$this->db->setQuery("Select count(*) as rows from #__jhtraq_users");
		return (int)$this->db->loadResult();
	}
	
	/**
	 * @name getCurrent
	 * @param none
	 * @return object
	 */
	function getCurrent()
	{
		$user =& JFactory::getUser();
		if((int)$user->id == 0)
		{
			$user->group_id = 3;
		}else{
			$user = $this->get($user->id);
		}
		return $user;
	}
}